<template>
  <view class="wrap" >
    <view class="comment">
      <view class="top">
        <view class="left">
          <view @tap.stop="toUserInfo(commentList.userId)" class="heart-photo">
            <image @tap.stop="toUserInfo(commentList.userId)" :src="commentList.avatar" mode=""></image>
          </view>
          <view class="user-info">
            <view @tap.stop="toUserInfo(commentList.userId)" class="name">{{ commentList.username }}</view>
            <view class="date">
              {{ formatTimeAgo(commentList.publishTime) }}
              {{ formatLocation(commentList.location) }}
            </view>
          </view>
        </view>
        <view class="right" :class="{ highlight: commentList.isLike }">
          {{ commentList.liked }}
          <u-icon v-if="!commentList.isLike" name="thumb-up" class="like" color="#9a9a9a" :size="30"
                  @click="getLike"></u-icon>
          <u-icon v-if="commentList.isLike" name="thumb-up-fill" class="like" :size="30" @click="getLike"></u-icon>
        </view>
      </view>
      <view class="content">{{ commentList.content }}</view>
    </view>
    <scroll-view scroll-y
                 :scroll-top="scrollTop"
                 scroll-with-animation
                 style="height: calc(100vh - env(safe-area-inset-bottom))">
      <view class="all-reply">
        <view >
        <childComment v-if="commentList.child != undefined"
                      :childCommentList="commentList.child"
                      :parentId="commentList.id"
                      :level="1"
                      :parentName = "commentList.username"
        />
          <view style="border-left: 1px solid rgba(192,192,192,0.44);
          border-bottom:  1px solid rgba(192,192,192,0.44);width: 64rpx;height: 120rpx;">

          </view>
        </view>
        <!--    空评论页面-->
        <view v-if="showEmptyComent" class="empty-comment">
          <image src="https://www.douluodalu.icu:9000/school/static/empty.png" style="width: 20vh;height: 20vh;">
          </image>
          <text>做ta的第一个暖场嘉宾</text>
          <!--评论页面-->
        </view>
        <view  style="height: 50px"></view>
      </view>
    </scroll-view>
  </view>
<!--      底部评论输入框-->
        <view class="bottom-list" :style="{bottom: keyboardHeight + 'px'}">
          &nbsp;&nbsp;
          <view>

      <textarea
          v-model="commentForm.content"
          fixed
          :focus="textareaFocus"
          :style="{width: textareaWidth + 'vw'}"
          :show-confirm-bar="false"
          :adjust-position="false"
          :placeholder="textareaPlaceholder"
          @focus="getKeyboardHeight"
          @blur="removeKeyboardHeight"
          @input="onTextareaInput"
          maxlength="-1"
          auto-height
      ></textarea>
            <view v-show="focusShow">
              <image @click="getMedia(item.type)"
                     style="padding: 0.5rem;width: 1.7rem;height: 1.7rem;margin: 0 5vw"
                     :src="item.url"
                     border="none"
                     :key="item.type" v-for="(item,index) in bottomList2">
              </image>
            </view>

          </view>
          <view v-show="!focusShow">
            <image @click="getMedia(item.type)"
                   style="padding: 0.5rem;width: 1.7rem;height: 1.7rem;"
                   :src="item.url"
                   border="none"
                   :key="item.type" v-for="(item,index) in bottomList">
            </image>

          </view>

          <view v-if="focusShow">
            <text style="color: #4ea4f9" @click="send(sendTrigger)">发送
            </text>
          </view>
          &nbsp;
        </view>

</template>

<script>

import {addComment, getCommentList, selectSchoolCommentById} from "@/api/comment";
import ChildComment from "@/components/comment/childComment.vue";
import {getToken} from "@/utils/auth";

export default {
  components: {ChildComment},
  props: ['comment'],
  data() {
    return {
      list: [{
        thumb: "https://cdn.uviewui.com/uview/goods/1.jpg"
      }, {
        thumb: "https://cdn.uviewui.com/uview/goods/2.jpg"
      }, {
        thumb: "https://cdn.uviewui.com/uview/goods/3.jpg"
      }, {
        thumb: "https://cdn.uviewui.com/uview/goods/4.jpg"
      }, {
        thumb: "https://cdn.uviewui.com/uview/goods/5.jpg"
      }],
      scrollTop: 0,
      sendTrigger:'comment',
      textareaPlaceholder: `回复 ${this.comment.username} :`,
      focusShow: false,
      textareaWidth: 60,
      textareaFocus: false,
      showEmptyComent: false,
      tempComment:[],
      maxHeight: '20px',
      maxLines: 4,
      showReplyPopup: false,
      //键盘高度
      keyboardHeight: 0,
      keyboardHeight1: 0,
      bottomList: [
        {
          url: 'https://www.douluodalu.icu:9000/school/static/voice.png',
          type: 1
        }, {
          url: 'https://www.douluodalu.icu:9000/school/static/post_image.png',
          type: 2
        }
      ],
      bottomList2: [{
        url: 'https://www.douluodalu.icu:9000/school/static/post_image.png',
        type: 1
      }, {
        url: 'https://www.douluodalu.icu:9000/school/static/voice.png',
        type: 3
      }, {
        url: 'https://www.douluodalu.icu:9000/school/static/post_emoj.png',
        type: 4
      }, {
        url: 'https://www.douluodalu.icu:9000/school/static/aite.png',
        type: 5
      }
      ],
      // 聊天框距离底部的高度
      bottomHeight: 0,
      childCommentIndex: null,
      childCommentInfo: [],
      commentForm: {
        content: '', // 内容
        images: '', // 图片
        videos: '', // 视频
        parentId: '',
        postId: '',
        rootCommentId: '',
      },
      show: false,
      loading: false,
      commentIndex: 0,
      current: 0,
      commentType: [
        { type: 1, name: "最热评论", url: "http://www.douluodalu.icu:9000/school/static/hot-comment.png" },
        {type: 2, name: '最新评论', url: 'http://www.douluodalu.icu:9000/school/static/new-comment.png'},
        {type: 3, name: '只看楼主', url: 'http://www.douluodalu.icu:9000/school/static/only-comment.png'},
        {type: 4, name: '有视频', url: 'http://www.douluodalu.icu:9000/school/static/video-comment.png'}
      ],
      channelInfo: {},
      commentList: [],
      postInfo: {},
      searchParams: {
        hot: true,
        latest: false,
        onlyOwner: false,
        haveVideo: false,
        pageSize: 15,
        current: 1,
        postId: ''
      }
    };
  },
  mounted() {
    this.commentList = this.comment
    if(this.commentList.child == undefined){
      this.showEmptyComent = true
    }
  },
  methods: {
    toUserInfo(userId){
      uni.navigateTo({
        url: '/pages/my/userInfo?id=' + userId
      })
    },
     send(trigger) {
       let token = getToken();
       if(!(token !== null && token !== ''&& token !== undefined)){
         uni.navigateTo({url: '/pages/my/login'})
         return;
       }
      if(trigger == 'comment'){
        this.sendComment()
      }else {
        this.sendCommentReply()
      }
    },
    async sendComment() {
            let token = getToken();
      if(!(token !== null && token !== ''&& token !== undefined)){
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      if (this.commentForm.content.trim() == '' || this.commentForm.content.trim().length == 0) {
        uni.showToast({
          title: '你还没有输入评论',
          icon: 'none'
        })
        return
      }
      this.commentForm.postId = this.comment.postId
      this.commentForm.parentId = this.comment.id
      this.commentForm.rootCommentId = this.comment.id
      const res = await addComment(this.commentForm)
      if(res.code == 200 && res.data?.id !== undefined){
        uni.pageScrollTo({
          scrollTop: 0, // 设置滚动到顶部的位置
          duration: 100 // 滚动动画时长，单位 ms
        });
        if (this.showEmptyComent && this.commentList.child == undefined && this.childCommentIndex == null) {
          // console.log("无子级")
          this.commentList.child = [res.data]

        }
        if (!this.showEmptyComent && this.commentList.child != undefined && this.childCommentIndex == null) {
          // console.log("有子级")
          this.commentList.child = [res.data, ...this.commentList.child]
        }
        this.showEmptyComent = false
      }else {
        uni.showToast({
          title: res.data,
          icon: 'none',
          duration: 2000
        })
      }


      this.scrollTop = this.scrollTop === 0 ? -1 : 0;
      this.commentForm.content = ''
      this.commentForm.videos = ''
      this.commentForm.images = ''
      this.commentForm.parentId = ''
      this.commentForm.rootCommentId = ''
      this.commentForm.postId = ''

      // this.getComment()
    },
    async sendCommentReply() {
      if (this.commentForm.content.trim() == '' || this.commentForm.content.trim().length == 0) {
        uni.showToast({
          title: '你还没有输入评论',
          icon: 'none'
        })
        return
      }
      this.commentForm.postId = this.comment.postId
      const res = await addComment(this.commentForm)
      if(res.code == 200 && res.data?.id !== undefined){
        await this.getComment()
        this.showEmptyComent = false
      }else {
        uni.showToast({
          title: res.data,
          icon: 'none',
          duration: 2000
        })
      }
      // uni.pageScrollTo({
      //   scrollTop: 0, // 设置滚动到顶部的位置
      //   duration: 100 // 滚动动画时长，单位 ms
      // });
      // this.scrollTop = this.scrollTop === 0 ? -1 : 0;
      this.commentForm.content = ''
      this.commentForm.videos = ''
      this.commentForm.images = ''
      this.commentForm.parentId = ''
      this.commentForm.rootCommentId = ''
      this.commentForm.postId = ''
      this.sendTrigger = 'comment'
    },
    reply(comment, index) {
            let token = getToken();
      if(!(token !== null && token !== ''&& token !== undefined)){
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
       this.sendTrigger = 'reply'
      this.commentForm.parentId = comment.id
      this.commentForm.rootCommentId = comment.rootCommentId
      // if (comment.child != undefined) {
        this.childCommentIndex = index
      // }
      this.textareaPlaceholder = `回复 ${comment.username} :`
      this.textareaFocus = true

    },
    async getComment() {
      let token = getToken();
      if(!(token !== null && token !== ''&& token !== undefined)){
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      this.searchParams.postId = this.comment.id
      const {data: res} = await selectSchoolCommentById(this.comment.id);
      this.commentList = res[0];

      if (this.commentList.child == null || this.commentList.child == [] || this.commentList.child == undefined) {
        this.showEmptyComent = true
      }
    },
    onTextareaInput() {
      // 在这里可以处理行数
    },
    getKeyboardHeight(event) {
      this.keyboardHeight = event.detail.height
      if (this.keyboardHeight < 0) this.keyboardHeight = 0;
      this.focusShow = true
      this.textareaWidth = 80
    },
    removeKeyboardHeight(event) {
      // 在这里可以处理键盘高度
      this.textareaPlaceholder = `回复 ${this.comment.username} :`,
      this.textareaFocus = false
      this.keyboardHeight = 0
      if (this.keyboardHeight < 0) this.keyboardHeight = 0;
      this.focusShow = false
      this.textareaWidth = 60
    },
    // 点赞
    getLike(index) {
            let token = getToken();
      if(!(token !== null && token !== ''&& token !== undefined)){
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      if (index === 0 || index > 0) {
        this.commentList[index].isLike = !this.commentList[index].isLike;
        if (this.commentList[index].isLike == true) {
          this.commentList[index].likeNum++;
        } else {
          this.commentList[index].likeNum--;
        }
      } else {
        if (this.comment.isLike == true) {
          this.comment.isLike = !this.comment.isLike;
          this.comment.likeNum--;
        } else {
          this.comment.isLike = !this.comment.isLike;
          this.comment.likeNum++;
        }
      }
    },
    formatTimeAgo(originalTimestamp) {
      const now = new Date();
      const timestampPlus8Hours = new Date(originalTimestamp);
      timestampPlus8Hours.setHours(timestampPlus8Hours.getHours() + 8);

      const timeDifference = now - timestampPlus8Hours;
      const seconds = Math.floor(timeDifference / 1000);
      const minutes = Math.floor(seconds / 60);
      const hours = Math.floor(minutes / 60);
      const days = Math.floor(hours / 24);
      const padZero = (num) => (num < 10 ? `0${num}` : num);

      if (days < 365) {
        if (days == 0) {
          if (hours >= 12) {
            return `${padZero(timestampPlus8Hours.getUTCMonth() + 1)}/${padZero(timestampPlus8Hours.getUTCDate())}`;
          } else if (hours > 0 && hours <= 12) {
            return `${hours}小时前`;
          } else if (minutes >= 1) {
            return `${minutes}分钟前`;
          } else {
            return '刚刚';
          }
        } else if (days == 1) {
          return `昨天 ${timestampPlus8Hours.getHours()}:${('0' + timestampPlus8Hours.getMinutes()).slice(-2)}`;
        } else {
          return `${padZero(timestampPlus8Hours.getUTCMonth() + 1)}/${padZero(timestampPlus8Hours.getUTCDate())}`;
        }
      } else {
        return `${timestampPlus8Hours.getUTCFullYear()}/${padZero(timestampPlus8Hours.getUTCMonth() + 1)}/${padZero(timestampPlus8Hours.getUTCDate())}`;
      }
    },
    formatLocation(location) {
      if (location == null) {
        return '未知';
      }
      location = location.replace(/省|市/g, '');

      return location;
    },
    // 回复列表
    getReply() {
    },
    notifyChoose(index) {
      this.commentIndex = index
      this.show = false
    },
    open() {
    },
    close() {
      this.show = false
    },
  }
};
</script>

<style lang="scss" scoped>
.empty-comment {
  height: 40vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: rgb(192, 192, 192);
}
.bottom-list {
  display: flex;
  align-items: center;
  bottom: 0;
  z-index: 999;
  width: 100vw;
  position: fixed;
  background-color: #fff;
  max-height: 12vh;
}

.wrap {
  height: calc(75vh);
  /* #ifdef H5 */
  height: calc(75vh - var(--window-top));
  /* #endif */
  display: flex;
  flex-direction: column;

}

.comment {
  padding: 30rpx;
  font-size: 32rpx;
  background-color: #ffffff;

  .top {
    display: flex;
    justify-content: space-between;
  }

  .left {
    display: flex;

    .heart-photo {
      image {
        width: 64rpx;
        height: 64rpx;
        border-radius: 50%;
        background-color: #f2f2f2;
      }
    }

    .user-info {
      margin-left: 10rpx;

      .name {
        color: $u-light-color;
        font-size: 28rpx;
        margin-bottom: 4rpx;
      }

      .date {
        font-size: 20rpx;
        color: $u-light-color;
        display: flex;
        align-items: center;
      }

      .reply {
        font-size: 20rpx;
        color: #9a9a9a;
        background-color: rgba(154, 154, 154, 0.14);
        border: none;
        padding: 2px 5px;
        border-radius: 5px;
        margin-left: 10rpx;
      }
    }
  }

  .right {
    display: flex;
    font-size: 20rpx;
    align-items: center;
    color: #9a9a9a;

    .like {
      margin-left: 6rpx;
    }

    .num {
      font-size: 26rpx;
      color: #9a9a9a;
    }
  }

  .highlight {
    color: #5677fc;

    .num {
      color: #5677fc;
    }
  }
}

textarea {
  background-color: rgba(154, 154, 154, 0.15);
  border-radius: 60rpx;
  padding: 8px;
  max-height: 12vh;
}

.all-reply {
  margin-top: 10rpx;
  padding-top: 20rpx;


  .all-reply-top {
    margin-left: 20rpx;
    padding-left: 20rpx;
    border-left: solid 4rpx #5677fc;
    font-size: 30rpx;
    font-weight: bold;


  }

  .item {
    border-bottom: solid 2rpx $u-border-color;
    background-color: rgb(245, 245, 245);
  }

  .reply {
    padding: 20rpx;
    background-color: rgb(242, 242, 242);
    border-radius: 12rpx;
    margin: 10rpx 0;

    .username {
      font-size: 24rpx;
      color: #7a7a7a;


    }
  }
}
</style>
